import { Form, Radio } from "antd";
import { Button, InputItem, List, Modal, TextareaItem, Toast, WhiteSpace } from 'antd-mobile';
import { addon } from "pao-aop";
import { BaseReactElement, BaseReactElementControl, BaseReactElementState, CookieUtil, reactControl } from "pao-aop-client";
import React from "react";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { COOKIE_KEY_CURRENT_USER } from "src/business/mainForm/backstageManageMainForm";
import { User } from "src/business/models/user";
import { setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from 'src/projects/app/appService';
import { beforeUpload, ROUTE_PATH, decodeUrlParam } from "src/projects/app/util-tool";
import { remote } from "src/projects/remote";

const alert = Modal.alert;
/**
 * 组件：补贴申请详情状态
 */
export interface ApplicationInsertViewState extends BaseReactElementState {
    imgHeight?: any;
    name?: any;
    sex?: any;
    phone?: any;
    id_card?: any;
    address?: any;
    reason?: any;
    idCardBack?: any;
    idCardFront?: any;
    household_register?: any;
    photo?: any;
    income?: any;
    special_status?: any;
    data?: any;
    person_info?: any;
    show?: any;
}
/**
 * 组件：补贴申请详情
 * 描述
 */
export class ApplicationInsertView extends BaseReactElement<ApplicationInsertViewControl, ApplicationInsertViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            name: '',
            sex: '',
            phone: '',
            id_card: '',
            address: '',
            reason: '',
            idCardBack: '',
            idCardFront: '',
            household_register: '',
            photo: '',
            income: '',
            special_status: '',
            data: [],
            person_info: {},
            show: false
        };
    }
    componentDidMount() {
        // 判断是否登录
        AppServiceUtility.personnel_service.get_user_session!()!
            .then((data: any) => {
                if (!data) {
                    this.props.history!.push(ROUTE_PATH.login);
                    return;
                }
            });
        let id = this.props.match!.params.key.split('&')[0];
        AppServiceUtility.allowance_service.get_allowance_project_list_all!({ "id": id })!
            .then((data: any) => {
                console.log(data.result);
                this.setState({
                    data: data.result[0]
                });
            });
        if (this.props.match!.params.key.split('&').length > 1) {
            this.setState({
                person_info: JSON.parse(decodeUrlParam(this.props.match!.params.key.split('&')[1]))
            });
            let person_info = JSON.parse(decodeUrlParam(this.props.match!.params.key.split('&')[1]));
            console.log(JSON.parse(decodeUrlParam(this.props.match!.params.key.split('&')[1])));
            this.setState({
                name: person_info.name,
                sex: person_info.personnel_info ? person_info.personnel_info.sex : '',
                phone: person_info.personnel_info ? person_info.personnel_info.telephone : '',
                id_card: person_info.id_card,
                address: person_info.personnel_info ? person_info.personnel_info.address : '',
            });
        } else {
            this.setState({
                show: true
            });
        }
    }

    submit = (): boolean => {
        let currentUserId = CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER).id;
        const { name, sex, phone, id_card, address, reason, idCardBack, idCardFront, household_register, photo, income, special_status, data } = this.state;
        if (!name) {
            Toast.fail('请输入姓名', 1);
            return false;
        }
        if (!sex) {
            Toast.fail('请选择你的性别', 1);
            return false;
        }
        if (!phone) {
            Toast.fail('请填写你的联系电话', 1);
            return false;
        }
        if (!id_card) {
            Toast.fail('请填写你的身份证', 1);
            return false;
        }
        if (!address) {
            Toast.fail('请填写你的地址', 1);
            return false;
        }
        if (!reason) {
            Toast.fail('请填写你的申请理由', 1);
            return false;
        }
        var param: any = {
            Operator: currentUserId,
            name: name,
            id_card: id_card,
            allowance_type: "养老补贴" + data.allowance_project_type,
            project_id: this.props.match!.params.key.split('&')[0],
            project_list: [
                {
                    ass_info: {
                        dataSource: [{ option_content: '男', score: "0", serial_number: "0" }, { option_content: '女', score: "0", serial_number: "1" }],
                        project_name: "性别",
                        selete_type: "1",
                        value: sex === '男' ? "0" : "1"
                    }
                },
                {
                    ass_info: {
                        project_name: "电话",
                        selete_type: "3",
                        value: phone
                    }
                },
                {
                    ass_info: {
                        project_name: "地址",
                        selete_type: "3",
                        value: address
                    }
                },
                {
                    ass_info: {
                        project_name: "申请理由",
                        selete_type: "3",
                        value: reason
                    }
                },
                {
                    ass_info: {
                        project_name: "身份证正面",
                        selete_type: "6",
                        value: idCardFront
                    }
                },
                {
                    ass_info: {
                        project_name: "身份证反面",
                        selete_type: "6",
                        value: idCardBack
                    }
                },
                {
                    ass_info: {
                        project_name: "户口簿证",
                        selete_type: "6",
                        value: household_register
                    }
                },
                {
                    ass_info: {
                        project_name: "本人照片",
                        selete_type: "6",
                        value: photo
                    }
                },
                {
                    ass_info: {
                        project_name: "收入证明",
                        selete_type: "6",
                        value: income
                    }
                },
                {
                    ass_info: {
                        project_name: "特殊身份证明",
                        selete_type: "6",
                        value: special_status
                    }
                },
            ]
        };
        console.log(param);
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('提交失败，请稍候再试', 3);
            },
            10000
        );
        // this.props.history!.push(ROUTE_PATH.applicationDetail);
        AppServiceUtility.allowance_service.update_allowance!(param)!
            .then((data: any) => {
                console.log(data);
                if (data === 'Success') {
                    console.log(data);
                    clearTimeout(st);
                    alert('申请成功', '你的申请信息已提交,请耐心等待结果', [
                        { text: '确认', onPress: () => this.props.history!.push(ROUTE_PATH.applicationSubsidies) },
                    ]);
                } else if (data === '同一个人每次只能申请一次同类型的补贴') {
                    Toast.fail('同一个人每次只能申请一次同类型的补贴,请勿重复申请', 3);
                } else if (data === '申请失败，系统中没有该长者信息') {
                    Toast.fail('申请失败，系统中没有该长者信息', 3);
                } else if (data === '申请失败，该长者所属的区域没有相关民政信息，请联系管理员') {
                    Toast.fail('申请失败，该长者所属的区域没有相关民政信息，请联系管理员', 3);
                } else {
                    Toast.fail('申请失败', 3);
                }
            });
        return false;
    }
    imgChange = (files: any, type: any, index: any) => {
        // this.setState({
        //     files
        //   });
        console.log(files);
        console.log(type);
        console.log(index);
    }
    nameChange = (value: any) => {
        console.log(value);
        this.setState({
            name: value
        });
    }
    sexChange = (e: any) => {
        console.log(e.target.value);
        this.setState({
            sex: e.target.value
        });
    }
    phoneChange = (value: any) => {
        console.log(value);
        this.setState({
            phone: value
        });
    }

    idCardChange = (value: any) => {
        console.log(value);
        this.setState({
            id_card: value
        });
    }

    addressChange = (value: any) => {
        console.log(value);
        this.setState({
            address: value
        });
    }

    reasonChange = (value: any) => {
        console.log(value);
        this.setState({
            reason: value
        });
    }

    idCardBackChange = (e: any) => {
        console.log(e);
        this.setState({
            idCardBack: e
        });
    }

    idCardFrontChange = (e: any) => {
        console.log(e);
        this.setState({
            idCardFront: e
        });
    }

    householdRegisterChange = (e: any) => {
        console.log(e);
        this.setState({
            household_register: e
        });
    }

    photoChange = (e: any) => {
        console.log(e);
        this.setState({
            photo: e
        });
    }

    incomeChange = (e: any) => {
        console.log(e);
        this.setState({
            income: e
        });
    }

    specialStatusChange = (e: any) => {
        console.log(e);
        this.setState({
            special_status: e
        });
    }
    render() {
        const { getFieldProps } = this.props.form;
        const { getFieldDecorator } = this.props.form!;
        setMainFormTitle("申请填写");
        return (
            <div>
                <Form>
                    <List>
                        <InputItem {...getFieldProps('name')} clear={true} placeholder="请输入姓名" onChange={this.nameChange} value={this.state.name}>申请人</InputItem>
                        <InputItem editable={false} labelNumber={10}>
                            性别&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <Radio.Group disabled={this.state.show} onChange={this.sexChange} value={this.state.sex}>
                                <Radio value={'男'}>男</Radio>
                                <Radio value={'女'}>女</Radio>
                            </Radio.Group>
                        </InputItem>
                        <InputItem {...getFieldProps('phone')} clear={true} placeholder="请输入联系电话" onChange={this.phoneChange} value={this.state.phone}>联系电话</InputItem>
                        <InputItem {...getFieldProps('id_card')} clear={true} placeholder="请输入身份证号码" onChange={this.idCardChange} value={this.state.id_card}>身份证号码</InputItem>
                        <InputItem {...getFieldProps('address')} clear={true} placeholder="请输入户籍地址" onChange={this.addressChange} value={this.state.address}>户籍地址</InputItem>
                    </List>
                    <List renderHeader={() => '申请理由或家庭情况描述'}>
                        <TextareaItem
                            {...getFieldProps('reason', {})}
                            rows={5}
                            count={1000}
                            placeholder='请输入申请理由或描述'
                            value={this.state.reason}
                            onChange={this.reasonChange}
                        />
                    </List>
                    <List renderHeader={() => '提交材料（注：资料齐全有助于申请成功）'}>
                        <List renderHeader={() => '身份证正面'}>
                            {getFieldDecorator('idCardFront', {
                                initialValue: this.state.idCardFront,
                                rules: [{
                                    required: false,
                                }],
                            })(
                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={this.idCardFrontChange} />
                            )}
                        </List>
                        <List renderHeader={() => '身份证反面'}>
                            {getFieldDecorator('idCradBack', {
                                initialValue: this.state.idCardBack,
                                rules: [{
                                    required: false,
                                }],
                            })(
                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={this.idCardBackChange} />
                            )}
                        </List>
                        <List renderHeader={() => '户口簿证'}>
                            {getFieldDecorator('household_register', {
                                initialValue: this.state.household_register,
                                rules: [{
                                    required: false,
                                }],
                            })(
                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={this.householdRegisterChange} />
                            )}
                        </List>
                        <List renderHeader={() => '本人照片'}>
                            {getFieldDecorator('photo', {
                                initialValue: this.state.photo,
                                rules: [{
                                    required: false,
                                }],
                            })(
                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={this.photoChange} />
                            )}
                        </List>
                        <List renderHeader={() => '收入证明（90岁不用提供）'}>
                            {getFieldDecorator('income', {
                                initialValue: this.state.income,
                                rules: [{
                                    required: false,
                                }],
                            })(
                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={this.incomeChange} />
                            )}
                        </List>
                        <List renderHeader={() => '特殊身份证明（90岁不用提供）'}>
                            {getFieldDecorator('special_status', {
                                initialValue: this.state.special_status,
                                rules: [{
                                    required: false,
                                }],
                            })(
                                <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} onChange={this.specialStatusChange} />
                            )}
                        </List>
                        {/* <Row type='flex' justify='center' style={{ height: '180px' }}>
                            <Col span={12} style={{ textAlign: 'center' }}><ImagePicker length={1} style={{ height: '120px', width: '120px', margin: '0 auto' }} /><p>收入证明</p><p>（90岁不用提供）</p></Col>
                            <Col span={12} style={{ textAlign: 'center' }}><ImagePicker length={1} style={{ height: '120px', width: '120px', margin: '0 auto' }} /><p>特殊身份证明</p><p>（90岁不用提供）</p></Col>
                        </Row> */}
                    </List>
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                    <WhiteSpace size="lg" />
                    <Button type="primary" style={{ position: 'fixed', bottom: '0px', width: '100%' }} onClick={this.submit}>提交申请</Button>
                </Form>
            </div >
        );
    }
}

/**
 * 控件：补贴申请详情控制器
 * 描述
 */
@addon('ApplicationInsertView', '补贴申请详情', '补贴申请详情')
@reactControl(Form.create<any>()(ApplicationInsertView), true)
export class ApplicationInsertViewControl extends BaseReactElementControl {
    constructor() {
        super();
    }
}